package com.xyht.sca_s.student_manage_system.common.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xyht.sca_s.student_manage_system.common.util.DynamicSchedulingTaskUtil;
import com.xyht.sca_s.student_manage_system.modules.attendance.entity.SmsSchedulingTask;
import com.xyht.sca_s.student_manage_system.modules.attendance.mapper.SmsSchedulingTaskMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

import static com.xyht.sca_s.student_manage_system.common.constant.CloseFlagConstant.IS_CLOSE_FALSE;

@Component
public class SchedulingTaskInitConfig {
    @Autowired
    private SmsSchedulingTaskMapper smsSchedulingTaskMapper;
    @Autowired
    private DynamicSchedulingTaskUtil dynamicSchedulingTaskUtil;

    @Bean
    public void initSchedulingTask() {
        List<SmsSchedulingTask> notExpirationTaskList = smsSchedulingTaskMapper.selectList(new QueryWrapper<SmsSchedulingTask>()
                .lambda()
                .gt(SmsSchedulingTask::getExpirationTime, new Date()));
        List<SmsSchedulingTask> expirationTaskList = smsSchedulingTaskMapper.selectList(new QueryWrapper<SmsSchedulingTask>()
                .lambda()
                .le(SmsSchedulingTask::getExpirationTime, new Date())
                .eq(SmsSchedulingTask::getIsClose, IS_CLOSE_FALSE));

        if (notExpirationTaskList != null && notExpirationTaskList.size()>1){
            for (SmsSchedulingTask task:notExpirationTaskList) {
                dynamicSchedulingTaskUtil.createTask(task.getName(),task.getType(),task.getExpirationTime());
            }
        }
        if (expirationTaskList != null && expirationTaskList.size()>1){
            for (SmsSchedulingTask task:expirationTaskList) {
                dynamicSchedulingTaskUtil.cancelTask(task.getName());
            }
        }
    }
}
